#include "dishesmanagement.h"
#include "ui_dishesmanagement.h"

dishesManagement::dishesManagement(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::dishesManagement)
{
    ui->setupUi(this);
    db = QSqlDatabase::database("conn");//链接数据库
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);
    ui->saveBtn->setShortcut(Qt::Key_Return);//设置保存快捷键为键盘的“回车”键

    //访问数据库的操作主要包括创建表，向数据库表中插入数据，删除数据，更新数据，查询数据
    //对于数据库中的表，通常只需要创建一次，而其他的操作是可以重复的

    QString sqlCreate = QString("create table if not exists menu(id integer primary key autoincrement,"
                                "name varchar(20),"
                                "ingredients varchar(40),"
                                "prize int,"
                                "number int);");//创建表单
    if(!query.exec(sqlCreate)){
        qDebug() << "create list error" << db.lastError();
    }
    initList();//初始化表单
}

dishesManagement::~dishesManagement()
{
    delete ui;
}

void dishesManagement::on_addBtn_clicked()//按下添加菜品按钮
{
    QMessageBox::information(this, "友情提示", "请填写要添加菜品的信息");
    clearEdit();//清除编辑栏内容
    editTrue();//编辑状态对菜品内容进行填写，点击保存按钮完成添加
}

void dishesManagement::on_saveBtn_clicked()//按下保存菜品按钮
{
    QString name = ui->nameEdit->text();
    QString ingredients = ui->ingredientsEdit->text();
    int prize = ui->prizeEdit->text().toInt();
    int number = ui->numberEdit->text().toInt();
    //获取数据
    if(name.isEmpty()||ingredients.isEmpty()){
        QMessageBox::information(this, "友情提示", "请填写完整的菜品信息");
        return;
    }

    QMessageBox::StandardButton free = QMessageBox::Yes,sellout = QMessageBox::Yes;
    if(prize == 0){//价格为零时，防止误操作
        free = QMessageBox::question(this,"友情提示","当前菜品价格为0，是否继续？");
    }
    if(free == QMessageBox::No || sellout == QMessageBox::No){
        return;
    }
    if(number == 0){//数量为零时，防止误操作
        sellout = QMessageBox::question(this,"友情提示","当前菜品数量为0，是否继续？");
    }
    if(free == QMessageBox::No || sellout == QMessageBox::No){
        return;
    }

    bool existFlag = false;//如果数据库中存在同名菜品，认定此时操作为修改，否则认定此时操作为添加
    int id = 0;//保存菜品id，便于修改时使用

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);//减少内存浪费
    QString sqlSelect = QString ("select * from menu;");

    if(!query.exec(sqlSelect)){//查找同名菜品
        qDebug() << "select data error" << db.lastError();
        return;
    }else {
        while(query.next()){
            id = query.value("id").toInt();
            if(query.value("name") != ui->nameEdit->text()){
                continue;
            }else{
                existFlag = true;
                break;
            }
        }
    }

    if(existFlag){//菜品存在，对菜品进行修改操作

        QString sqlUpdate = QString("update menu set name = '%1',"
                                    "ingredients = '%2',"
                                    "prize = %3,"
                                    "number = %4 "
                                    "where id = %5").arg(name).arg(ingredients).arg(prize).arg(number).arg(id);
        //    UPDATE table_name
        //    SET column1 = value1, column2 = value2...., columnN = valueN
        //    WHERE [condition];

        if(!query.exec(sqlUpdate)){
            qDebug() << "update data error" << db.lastError();
        }else{
            QMessageBox::information(this, "友情提示", "修改菜品成功");
        }
    }else{//菜品不存在，对菜品进行添加操作

        QString sqlInsert = QString("insert into menu (name,ingredients,prize,number) "
                                    "values('%1','%2',%3,%4);").arg(name)
                .arg(ingredients).arg(prize).arg(number);

        if(!query.exec(sqlInsert)){
            qDebug() << "insert data error" << db.lastError();
        }else{
            QMessageBox::information(this, "友情提示", "添加菜品成功");
        }
    }

    clearEdit();//清除编辑栏内容
    editFalse();//内容上传，编辑结束
    initList();//刷新表
}

void dishesManagement::on_deleteBtn_clicked()//按下删除菜品按钮
{
    if(ui->nameEdit->text().isEmpty()){
        QMessageBox::information(this, "友情提示", "请填写要删除菜品的名称");
        return;
    }
    QString name = ui->nameEdit->text();
    QString sqlDelete = QString("delete from menu where name = '%1'").arg(name);
    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联

    if(!query.exec(sqlDelete)){
        qDebug() << "delete data error" << db.lastError();
    }else{
        QMessageBox::information(this, "友情提示", "删除菜品成功");
    }//删除菜品操作

    clearEdit();//清空编辑栏数据
    editFalse();//不可编辑状态
    initList();//刷新表
}

void dishesManagement::on_searchBtn_clicked()//按下查找菜品按钮
{
    clearEdit();//清除编辑栏内容
    editFalse();
    QString keyword = QInputDialog::getText(this, "查找菜品", "请输入要查找的菜名：");//获取查找菜名
    if(!keyword.isEmpty()){

        QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
        query.setForwardOnly(true);//减少内存浪费
        QString sqlSelect = QString ("select * from menu where name = '%1';").arg(keyword);

        if(!query.exec(sqlSelect)){//查找关键字
            qDebug() << "search data error" << db.lastError();
            return;
        }else {
            if(query.next()){
                ui->nameEdit->setText(query.value("name").toString());
                ui->ingredientsEdit->setText(query.value("ingredients").toString());
                ui->prizeEdit->setText(query.value("prize").toString());
                ui->numberEdit->setText(query.value("number").toString());
                //显示结果到编辑框，等待编辑
                editTrue();//查找到菜品，进行编辑操作
            }else{
                QMessageBox::information(this,"友情提示","没有此菜品，请确认输入是否正确");
            }
        }
    }else{
        QMessageBox::information(this,"友情提示","请输入菜品名称");
    }
}

void dishesManagement::on_dishesList_itemClicked(QListWidgetItem *item)//单击列表中的菜品
{
    itemForm* dishes =dynamic_cast<itemForm*>(ui->dishesList->itemWidget(item));//获取列表元素对应的的itemForm
    QString name = dishes->getName();//获取对应菜品名称

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);//减少内存浪费
    QString sqlSelect = QString ("select * from menu where name = '%1';").arg(name);

    if(!query.exec(sqlSelect)){//查找关键字
        qDebug() << "search data error" << db.lastError();
        return;
    }else {
        if(query.next()){
            ui->nameEdit->setText(query.value("name").toString());
            ui->ingredientsEdit->setText(query.value("ingredients").toString());
            ui->prizeEdit->setText(query.value("prize").toString());
            ui->numberEdit->setText(query.value("number").toString());
            editTrue();//显示信息到编辑框，等待编辑
        }
    }
}

void dishesManagement::initList()//刷新表
{
    ui->dishesList->clear();//清空表格

    QSqlQuery query;//创建对象时，系统会自动完成跟数据库的关联
    query.setForwardOnly(true);

    QString sqlSelect = QString ("select * from menu;");
    if(!query.exec(sqlSelect)){//遍历menu表单
        qDebug() << "insert data error" << db.lastError();
    }else {
        while(query.next()){//读取数据库，填写表单
            QString iniName = query.value("name").toString();
            QString iniIngredients = query.value("ingredients").toString();
            int iniPrize = query.value("prize").toInt();
            int iniNumber = query.value("number").toInt();
            itemForm* dishesItem = new itemForm;
            dishesItem->setDishes(iniName,iniIngredients,iniPrize,iniNumber);
            QListWidgetItem* item = new QListWidgetItem;

            item->setSizeHint(QSize(700,70));
            ui->dishesList->addItem(item);
            ui->dishesList->setItemWidget(item,dishesItem);
        }
    }
}

void dishesManagement::clearEdit()//清空编辑框
{
    ui->nameEdit->clear();
    ui->ingredientsEdit->clear();
    ui->prizeEdit->clear();
    ui->numberEdit->clear();
}

void dishesManagement::editTrue()//可编辑
{
    ui->nameEdit->setReadOnly(false);
    ui->ingredientsEdit->setReadOnly(false);
    ui->prizeEdit->setReadOnly(false);
    ui->numberEdit->setReadOnly(false);
}

void dishesManagement::editFalse()//不可编辑
{
    ui->nameEdit->setReadOnly(true);
    ui->ingredientsEdit->setReadOnly(true);
    ui->prizeEdit->setReadOnly(true);
    ui->numberEdit->setReadOnly(true);
}
